package com.guiji.text2video.fastvideo.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guiji.text2video.common.core.utils.SecurityUtils;
import com.guiji.text2video.common.core.web.controller.BaseController;
import com.guiji.text2video.common.core.web.domain.AjaxResult;
import com.guiji.text2video.common.redis.service.RedisService;
import com.guiji.text2video.fastvideo.domain.vo.NewsSimplePushVO;
import com.guiji.text2video.fastvideo.domain.vo.Text2videoJobScheduleStat;
import com.guiji.text2video.fastvideo.domain.vo.Text2videoPoolsStat;
import com.guiji.text2video.fastvideo.service.INLPService;
import com.guiji.text2video.fastvideo.service.IText2videoJobScheduleStatService;
import com.guiji.text2video.fastvideo.service.IText2videoJobService;
import com.guiji.text2video.fastvideo.service.IText2videoPoolsStatService;
import com.guiji.text2video.fastvideo.task.JobStatTimingTask;
import com.guiji.text2video.fastvideo.task.PoolsStatTimingTask;
import com.guiji.text2video.fastvideo.vo.PushVideoVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @program: ruoyi
 * @description: 监控controller
 * @author: sunchengliang
 * @create:
 **/

@RestController
@RequestMapping("/job-monitor")
public class JobMonitorController extends BaseController {

    @Autowired
    JobStatTimingTask jobStatTimingTask;

    @Autowired
    PoolsStatTimingTask poolsStatTimingTask;

    @Autowired
    private INLPService NLPService;

    @Resource
    private RedisService redisService;
    @Autowired
    private IText2videoJobService text2videoJobService;

    @Autowired
    private IText2videoJobScheduleStatService jobScheduleStat;

    @Autowired
    IText2videoPoolsStatService PoolsStat;

    private Logger logger = LoggerFactory.getLogger(JobMonitorController.class);

    @PostMapping("/deletevideo")
    public AjaxResult deletevideo(@RequestBody PushVideoVO pv) {

        Collection<String> collections = redisService.keys(pv.getCategory() + "*");
        logger.info("删除:{}个数：{}", pv.getCategory(), collections.size());
        if (collections.size() == 0) {
            return AjaxResult.success();
        }
        Iterator iter = collections.iterator();
        while (iter.hasNext()) {
            String redisKey = (String) iter.next();
            redisService.deleteObject(redisKey);
        }
        return AjaxResult.success();
    }


    @PostMapping("/pushvideo")
    public AjaxResult pushvideo(@RequestBody PushVideoVO pv) {
        String url = pv.getNginxUrl();


        switch (pv.getCategory()){
            case "sanguo":
                setRedisVideo(url, "shenhualishimingzhupingshuo", "陪你看三国", "sanguo");
                break;
            case "shuihu":
                setRedisVideo(url, "huishuolishi", "慧说水浒", "shuihu");
                break;
            case "honglou":
                setRedisVideo(url, "hongloumeng", "红楼人物故事评说", "honglou");
                break;
        }

        return AjaxResult.success();
    }

    private void setRedisVideo(String url, String username, String channel, String redisfor) {

        HttpResponse response = HttpRequest.get(url).execute();
        String resp = response.body();
        String pattern = "Job.*?Job.*?\\.";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(resp);
        int i = 1;
        while (m.find()) {
            NewsSimplePushVO vo = new NewsSimplePushVO();

            String temp = m.group();
            String pattern1 = "Job.*?mp4";
            Pattern p1 = Pattern.compile(pattern1);
            Matcher m1 = p1.matcher(temp);
            while (m1.find()) {
                vo.setPath(URLUtil.decode(url + m1.group()));
                temp = URLUtil.decode(url + m1.group());
            }
            String title = temp.replaceAll("http.*?Job-.*?-.*?-.*?-", "").replaceAll(".mp4","");
            vo.setTitle(title);
            vo.setDescription(title);
            vo.setUsername(username);
            vo.setChannel(channel);
            redisService.setCacheObject(redisfor + "-" + i, JSONUtil.parseObj(vo).toString());
            i = i + 1;
        }
        Collection<String> collections = redisService.keys(redisfor + "-*");
        logger.info("存入redis大小：{}", collections.size());

    }


    /**
     * 任务监控
     */

    @GetMapping("/poolsStatus")
    //@PreAuthorize(hasAnyPermi = "@ss.hasRole('user')")
    public AjaxResult pools(@RequestParam(value = "time") Date time) throws Exception {
        if (ObjectUtil.isEmpty(time)) {
            time = DateUtil.offset(new Date(), DateField.HOUR, -1);
        }
        int gap = PoolsStat.getCombineGap(time);

        List<HashMap> list;
        List<HashMap> newList;
        try {
            Text2videoPoolsStat pools = new Text2videoPoolsStat();
            pools.setCreateTime(time);
            list = PoolsStat.selectStat(pools);
            newList = PoolsStat.combineByTime(list, time, gap);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("查询出错");
        }

        Map<String, Object> resMap = new HashMap<>(10);
        resMap.put("list", newList);
        return AjaxResult.success(resMap);
    }


    /**
     * 统计任务执行性能，并且提供历史下载。
     */

    @PostMapping("/jobStat")
    public AjaxResult jobStat(
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "15") Integer pageSize,
            @RequestBody Text2videoJobScheduleStat jss) throws Exception {

        Long userId = SecurityUtils.getUserId();
        //logger.error(jss.toString());
        //设置分页
        PageInfo pageInfo;
        try {
            PageHelper.startPage(pageNum, pageSize);
            List<Text2videoJobScheduleStat> list = jobScheduleStat.selectJobScheduleStatPage(jss);
            pageInfo = new PageInfo(list);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("查询出错");
        }
        Map<String, Object> resMap = new HashMap<>(10);
        resMap.put("list", pageInfo.getList());
        resMap.put("total", pageInfo.getTotal());
        resMap.put("pageNum", pageInfo.getPageNum());
        resMap.put("pageSize", pageInfo.getSize());
        resMap.put("pages", pageInfo.getPages());
        return AjaxResult.success(resMap);
    }


    /**
     * 返回正在执行的任务状态
     */

    @GetMapping("/jobRunning")
    public AjaxResult jobOnline() {

        Long userId = SecurityUtils.getUserId();

        List<Text2videoJobScheduleStat> list = jobScheduleStat.runningJobs();

        Map<String, Object> resMap = new HashMap<>(10);
        resMap.put("list", list);
        return AjaxResult.success(resMap);
    }

    /**
     * 定时接口统计job状态
     */

    @GetMapping("/statJob")
    public AjaxResult statJob() {

        jobStatTimingTask.upgradeJobScheduleStat();

        return AjaxResult.success();
    }

    /**
     * 更新线程池状态
     */

    @GetMapping("/statPools")
    public AjaxResult statPools() {

        poolsStatTimingTask.upgradePoolsStat();

        return AjaxResult.success();
    }

    /**
     * 统计未完成的zip任务
     *
     * @return
     */
    @GetMapping("/calculateUncommit")
    public AjaxResult calculateUncommit() {

        HashMap map = text2videoJobService.calculateUncommit();

        return AjaxResult.success(map);
    }


}